﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Loki.Utils;

namespace Loki.Commands
{
    /// <summary>
    /// Command manager class.
    /// </summary>
    public class CommandManager : LokiObject, IDisposable
    {
        /// <summary>
        /// The Always functor (for can execute test).
        /// </summary>
        /// <param name="P_Sender">The sender.</param>
        /// <param name="e">The <see cref="Loki.UI.CanExecuteCommandEventArgs"/> instance containing the event data.</param>
        public static void Always(object P_Sender, CanExecuteCommandEventArgs e)
        {
            e.CanExecute = true;
        }

        public CommandManager()
            : this(null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CommandManager"/> class.
        /// </summary>
        /// <param name="P_StateObject">The state object.</param>
        public CommandManager(ICommandAware P_StateObject)
        {
            _Commands = new ConcurrentDictionary<string, ICommand>();
            _Handlers = new ConcurrentDictionary<ICommand, List<ICommandHandler>>();
            _StateObject = P_StateObject;
        }

        private ICommandAware _StateObject = null;

        #region Commands
        public ICommand Create()
        {
            return Create(false);
        }

        /// <summary>
        /// Creates the specified command.
        /// </summary>
        /// <param name="P_DeepCommand">If set to <c>true</c> the command is a deep command.</param>
        public ICommand Create(bool P_DeepCommand)
        {
            return Create(P_DeepCommand, Guid.NewGuid().ToString());
        }

        public ICommand Create(string P_CommandName)
        {
            return Create(false, P_CommandName);
        }

        /// <summary>
        /// Creates the command with the specified name.
        /// </summary>
        /// <param name="P_DeepCommand">If set to <c>true</c> the command is a deep command.</param>
        /// <param name="P_CommandName">Name of the command.</param>
        public ICommand Create(bool P_DeepCommand, string P_CommandName)
        {
            _Commands[P_CommandName] = LokiServices.Command.CreateCommand(P_DeepCommand, P_CommandName);
            return _Commands[P_CommandName];
        }

        private ConcurrentDictionary<string, ICommand> _Commands;

        private void ClearCommands()
        {
            foreach (ICommand L_Command in _Commands.Values)
            {
                LokiServices.Command.UnregisterCommand(L_Command);
            }

            _Commands.Clear();
        }
        #endregion

        #region Handlers
        public void Handle(ICommand P_Command, Action<object, CanExecuteCommandEventArgs> P_CanExecute, Action<object, CommandEventArgs> P_Execute, Func<CommandEventArgs, bool> P_ConfirmDelegate)
        {
            if (!_Handlers.ContainsKey(P_Command))
            {
                _Handlers[P_Command] = new List<ICommandHandler>();
            }

            _Handlers[P_Command].Add(LokiServices.Command.CreateHandler(P_Command, P_CanExecute, P_Execute, _StateObject, P_ConfirmDelegate));
        }

        public void Handle(ICommand P_Command, Action<object, CanExecuteCommandEventArgs> P_CanExecute, Action<object, CommandEventArgs> P_Execute)
        {
            Handle(P_Command, P_CanExecute, P_Execute, null);
        }

        public void Handle(ICommand P_Command, Action<object, CommandEventArgs> P_Execute)
        {
            Handle(P_Command, CommandManager.Always, P_Execute, null);
        }

        public void Handle(ICommand P_Command, Action<object, CommandEventArgs> P_Execute, Func<CommandEventArgs, bool> P_ConfirmDelegate)
        {
            Handle(P_Command, CommandManager.Always, P_Execute, P_ConfirmDelegate);
        }

        public void UnHandle(ICommand P_Command, Action<object, CanExecuteCommandEventArgs> P_CanExecute, Action<object, CommandEventArgs> P_Execute, Func<CommandEventArgs, bool> P_ConfirmDelegate = null)
        {
            if (_Handlers.ContainsKey(P_Command))
            {
                _Handlers[P_Command].Remove(LokiServices.Command.CreateHandler(P_Command, P_CanExecute, P_Execute, _StateObject, P_ConfirmDelegate));
            }
        }

        public void UnHandle(ICommand P_Command)
        {
            if (_Handlers.ContainsKey(P_Command))
            {
                foreach (ICommandHandler L_item in _Handlers[P_Command])
                {
                    LokiServices.Command.RemoveHandler(P_Command, L_item);
                }

                List<ICommandHandler> L_Removed = null;
                _Handlers.TryRemove(P_Command, out L_Removed);
            }
        }

        private ConcurrentDictionary<ICommand, List<ICommandHandler>> _Handlers;

        private void ClearHandlers()
        {
            foreach (KeyValuePair<ICommand, List<ICommandHandler>> L_Handler in _Handlers)
            {
                foreach (ICommandHandler L_Item in L_Handler.Value)
                {
                    LokiServices.Command.RemoveHandler(L_Handler.Key, L_Item);
                }
            }

            _Handlers.Clear();
        }
        #endregion

        #region Dispose
        /// <summary>
        /// Releases all resources used by an instance of the <see cref="CommandManager" /> class.
        /// </summary>
        /// <remarks>
        /// This method calls the virtual <see cref="Dispose(bool)" /> method, passing in <strong>true</strong>, and then suppresses 
        /// finalization of the instance.
        /// </remarks>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~CommandManager()
        {
            Dispose(false);
        }

        /// <summary>
        /// Releases the unmanaged resources used by an instance of the <see cref="CommandManager" /> class and optionally releases the managed resources.
        /// </summary>
        /// <param name="P_Disposing">Set <strong>true</strong> to release both managed and unmanaged resources; <strong>false</strong> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool P_Disposing)
        {
            if (P_Disposing)
            {
                ClearCommands();
                ClearHandlers();
                _StateObject = null;
            }
        }
        #endregion
    }
}
